/*
 * Copyright 2009 BioTeam Inc
 * 
 * Licensed under License GNU LESSER GENERAL PUBLIC LICENSE version 3.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.gnu.org/copyleft/lesser.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package net.bioteam.appweb.gwt.apps.client.user;

import net.bioteam.appweb.gwt.apps.client.StaticHolder;
import net.bioteam.appweb.gwt.apps.client.Util.GridPager;
import net.bioteam.appweb.gwt.apps.client.Util.Util;
import net.bioteam.appweb.gwt.apps.client.datatree.DataTreeDataSource;
import net.bioteam.appweb.gwt.apps.client.program.MyDataItem;
import net.bioteam.appweb.gwt.apps.clientandserver.Constant;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.History;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.DragDataAction;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.util.BooleanCallback;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.ImgButton;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.events.DragStartEvent;
import com.smartgwt.client.widgets.events.DragStartHandler;
import com.smartgwt.client.widgets.events.DrawEvent;
import com.smartgwt.client.widgets.events.DrawHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.grid.CellFormatter;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.SectionStack;
import com.smartgwt.client.widgets.layout.SectionStackSection;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.layout.VStack;
import com.smartgwt.client.widgets.menu.Menu;
import com.smartgwt.client.widgets.menu.MenuItem;
import com.smartgwt.client.widgets.menu.MenuItemIfFunction;
import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;
import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.tab.TabSet;
import com.smartgwt.client.widgets.tab.events.TabSelectedEvent;
import com.smartgwt.client.widgets.tab.events.TabSelectedHandler;
import com.smartgwt.client.widgets.tree.Tree;
import com.smartgwt.client.widgets.tree.TreeGrid;
import com.smartgwt.client.widgets.tree.TreeGridField;
import com.smartgwt.client.widgets.tree.TreeNode;
import com.smartgwt.client.widgets.tree.events.LeafClickEvent;
import com.smartgwt.client.widgets.tree.events.LeafClickHandler;

public class JobPanel extends HLayout
{

	TreeNode jobRootNode;

	public TreeNode getJobRootNode()
	{
		return jobRootNode;
	}

	public TreeGrid getJobFiles()
	{
		return jobFiles;
	}

	TreeGrid jobFiles;

	TabSet ts;

	public TabSet getTs()
	{
		return ts;
	}

	VLayout fileLayout;

	public VLayout getFileLayout()
	{
		return fileLayout;
	}

	public void setTs(TabSet ts)
	{
		this.ts = ts;
	}

	public JobPanel()
	{
		super();
		// setBorder("3px solid dark");
		setWidth100();
		setHeight100();

		setID("_jobPanel");
		// jobGridContainer.setAutoHeight();
		JobGrid jobGrid = new JobGrid();
		StaticHolder.jobGrid = jobGrid;

		ImgButton refresh = new ImgButton();
		refresh.setSrc("[SKIN]actions/refresh.png");
		refresh.setSize(16);
		refresh.setShowFocused(false);
		refresh.setShowRollOver(false);
		refresh.setShowDown(false);
		refresh.setPrompt("reload");
		refresh.addClickHandler(new ClickHandler()
		{

			public void onClick(ClickEvent event)
			{
				StaticHolder.jobGrid.reload();
			}
		});
		ImgButton delete = new ImgButton();
		delete.setSrc("[SKIN]actions/remove.png");
		delete.setSize(16);
		delete.setShowFocused(false);
		delete.setShowRollOver(false);
		delete.setShowDown(false);
		delete.setPrompt("Click to remove selected jobs");
		delete.addClickHandler(new ClickHandler()
		{

			public void onClick(ClickEvent event)
			{
				final JobGrid jobGrid = StaticHolder.jobGrid;
				if (jobGrid.getSelection().length == 0)
				{
					SC.say("No job is selected");
				} else
				{
					BooleanCallback callback = new BooleanCallback()
					{

						public void execute(Boolean value)
						{
							if (value != null && value)
							{
								if (jobGrid.getSelection().length > 5)
								{
									JobsDataSource src = (JobsDataSource) jobGrid.getDataSource();
									src.executeBatchRemove(jobGrid.getSelection(), jobGrid);
								} else
								{
									jobGrid.removeSelectedData();
								}
							}
						}

					};
					SC.confirm(jobGrid.getSelection().length + " selected jobs will be deleted", callback);
				}

				// StaticHolder.jobGrid.reload();
			}
		});

		Canvas jobs = new GridPager(jobGrid, 20, new Canvas[] { refresh, delete });

		ts = new TabSet();
		ts.setWidth(JobGrid.JobGridWidth + 20);
		ts.setHeight100();

		// ------------job list grid.
		Tab jobsTab = new Tab("Jobs");
		jobsTab.setPane(jobs);
		ts.addTab(jobsTab);

		// ---------------job detail grid
		Tab detailTab = new Tab("Detail");
		JobDetailGrid detailGrid = new JobDetailGrid();
		StaticHolder.jobDetailGrid = detailGrid;
		SectionStack detailContainer = new SectionStack();
		detailContainer.setHeight100();
		detailContainer.setWidth(JobGrid.JobGridWidth - 50);

		SectionStackSection section = new SectionStackSection();
		section.setCanCollapse(false);
		section.setExpanded(true);

		ImgButton refresh1 = new ImgButton();
		refresh1.setSrc("[SKIN]actions/refresh.png");
		refresh1.setSize(16);
		refresh1.setShowFocused(false);
		refresh1.setShowRollOver(false);
		refresh1.setShowDown(false);
		refresh1.setPrompt("Click to reload job");
		refresh1.addClickHandler(new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{
				StaticHolder.jobDetailGrid.reload();
			}
		});

		section.setControls(refresh1);
		section.setItems(detailGrid);
		detailContainer.setSections(section);

		detailTab.setPane(detailContainer);
		ts.addTab(detailTab);

		ts.addTabSelectedHandler(new TabSelectedHandler()
		{

			public void onTabSelected(TabSelectedEvent event)
			{
				if (event.getTabNum() == 0)
				{
					StaticHolder.jobGrid.load();
				} else
				{
					StaticHolder.jobDetailGrid.updateFileTree();
				}
			}
		});

		addMember(ts);
		// -----------------job files
		fileLayout = new VLayout();
		fileLayout.setHeight100();
		fileLayout.setWidth(320);

		createJobFilesTreeGrid();
		// jobFiles.setVisible(false);
		fileLayout.addMember(jobFiles);

		// ----------------------arrows
		VStack labelStack = new VStack();
		labelStack.setWidth(300);
		labelStack.setHeight(45);

		// LayoutSpacer spacer1 = new LayoutSpacer();
		// spacer1.setHeight(50);
		// labelStack.addMember(spacer1);

		Label label = new Label("Drag to copy");
		label.setIcon("[SKIN]/actions/sort_descending.png");
		// label.setIcon("arrow_right.png");
		label.setIconOrientation("middle");
		label.setHeight(20);
		label.setLayoutAlign(Alignment.CENTER);
		label.setWidth(150);
		labelStack.addMember(label);

		Label info = new Label("Right Click for action");
		info.setHeight(20);
		// info.setBackgroundColor("yellow");
		info.setLayoutAlign(Alignment.CENTER);
		info.setWidth(150);

		labelStack.addMember(info);
		fileLayout.addMember(labelStack);

		addMember(fileLayout);
	}

	private void createJobFilesTreeGrid()
	{
		jobFiles = new TreeGrid();
		jobFiles.setWidth(300);
		jobFiles.setHeight(200);

		jobFiles.setAnimateFolders(false);
		jobFiles.setShowHeader(true);
		jobFiles.setCanEdit(false);
		jobFiles.setCanDrop(false);
		jobFiles.setCanDragRecordsOut(true);
		jobFiles.setDragDataAction(DragDataAction.COPY);

		jobFiles.addDragStartHandler(new DragStartHandler()
		{

			public void onDragStart(DragStartEvent event)
			{
				TreeNode node = (TreeNode) jobFiles.getSelectedRecord();

				String path = "/" + Constant.job_name + jobFiles.getTree().getPath(node);
				StaticHolder.getDataTreeGrid().jobFileSrcPath = path;
				GWT.log("path is " + path, null);
			}
		});

		jobFiles.addLeafClickHandler(new LeafClickHandler()
		{

			public void onLeafClick(LeafClickEvent event)
			{
				TreeNode treeNode = event.getLeaf();
				String href = treeNode.getAttributeAsString("href");
				if (href != null)
				{
					Util.open(href);
				}

			}
		});

		TreeGridField tf = new TreeGridField("name", "Job Files", 250);
		tf.setCanToggle(false);
		tf.setCanSort(false);
		tf.setTreeField(true);
		tf.setType(ListGridFieldType.TEXT);

		TreeGridField sizeTf = new TreeGridField("size", "Size", 50);
		sizeTf.setCanToggle(false);
		sizeTf.setCanSort(false);
		sizeTf.setTreeField(false);
		sizeTf.setType(ListGridFieldType.TEXT);
		// sizeTf.set

		sizeTf.setCellFormatter(new CellFormatter()
		{

			public String format(Object value, ListGridRecord record, int rowNum, int colNum)
			{
				if (value == null)
					return "";
				int size = Integer.parseInt(value.toString());

				if (size > 1024 * 1024)
					return (size / (1024 * 1024)) + "M";
				else if (size > 1024)
					return (size / 1024) + "K";
				else
					return String.valueOf(size);
			}
		});

		jobFiles.setFields(tf, sizeTf);

		TreeNode[] nodes = new TreeNode[1];
		jobRootNode = new TreeNode();
		nodes[0] = jobRootNode;
		jobRootNode.setAttribute("id", 1);
		jobRootNode.setAttribute("name", "No Job Selected");
		jobRootNode.setAttribute("servername", "NoJob");
		jobRootNode.setAttribute("folder", true);

		final DataTreeDataSource src = new DataTreeDataSource()
		{

			public String myTranslatePath(String path)
			{

				return super.myTranslatePath("/" + Constant.job_name + path);
			}

			// this method is called when a drag out occurs
			// http://forums.smartclient.com/showthread.php?t=4963
			@Override
			protected void executeUpdate(final String requestId, final DSRequest request, final DSResponse response)
			{
			}

			protected void executeAdd(final String requestId, final DSRequest request, final DSResponse response)
			{

			}

			protected void executeRemove(final String requestId, final DSRequest request, final DSResponse response)
			{

			}

		};

		jobFiles.setInitialData(nodes);
		jobFiles.setLoadDataOnDemand(true);
		jobFiles.setDataSource(src);
		src.treeGrid = jobFiles;

		final Menu menu = new Menu();
		menu.setShowShadow(true);
		menu.setShadowDepth(10);

		final MenuItem dItem = new MenuItem("Download As Zip");
		final MenuItem aItem = new MenuItem("Analyze");
		final MenuItem vItem = new MenuItem("View");
		final MenuItem rItem = new MenuItem("Reload");
		final MenuItem pItem = new MenuItem("To PDF");

		dItem.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler()
		{
			public void onClick(MenuItemClickEvent event)
			{
				TreeNode treeNode = (TreeNode) jobFiles.getSelectedRecord();
				if (treeNode.getAttributeAsBoolean("folder"))
				{
					String href = treeNode.getAttributeAsString("href");
					Util.open(href + ".zip?zip=true");
					return;
				}
			}
		});
		dItem.setEnableIfCondition(new MenuItemIfFunction()
		{

			public boolean execute(Canvas target, Menu menu, MenuItem item)
			{
				TreeNode node = (TreeNode) jobFiles.getRecord(jobFiles.getEventRow());
				return node.getAttributeAsBoolean("folder");
			}
		});
		rItem.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler()
		{
			public void onClick(MenuItemClickEvent event)
			{
				TreeNode node = (TreeNode) jobFiles.getSelectedRecord();
				GWT.log("event row for reload  is" + jobFiles.getEventRow(), null);
				jobFiles.getTree().reloadChildren(node);
				// jobFiles.fetchData();
			}
		});
		rItem.setEnableIfCondition(new MenuItemIfFunction()
		{

			public boolean execute(Canvas target, Menu menu, MenuItem item)
			{
				TreeNode node = (TreeNode) jobFiles.getRecord(jobFiles.getEventRow());
				GWT.log("event row for enable condition  is" + jobFiles.getEventRow(), null);
				return node.getAttributeAsBoolean("folder");
			}
		});

		aItem.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler()
		{
			public void onClick(MenuItemClickEvent event)
			{
				// make sure it is initialized.
				DynamicForm form = StaticHolder.getDataInputPanel().inputForm;
				form.clearValues();
				StaticHolder.getDataInputPanel().restoreDefaultMessage();
				TreeNode node = (TreeNode) jobFiles.getSelectedRecord();
				String path = src.myTranslatePath(jobFiles.getTree().getPath(node));
				MyDataItem fileInput = StaticHolder.getDataInputPanel().fileInput;
				fileInput.serverFile.setValue(path);
				fileInput.redraw();
				fileInput.radioGroupItem.setValue("Server File");
				History.newItem("user_analysis_1");

			}
		});
		aItem.setEnableIfCondition(new MenuItemIfFunction()
		{

			public boolean execute(Canvas target, Menu menu, MenuItem item)
			{
				TreeNode node = (TreeNode) jobFiles.getRecord(jobFiles.getEventRow());
				return !node.getAttributeAsBoolean("folder");
			}
		});
		vItem.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler()
		{
			public void onClick(MenuItemClickEvent event)
			{
				TreeNode treeNode = (TreeNode) jobFiles.getSelectedRecord();
				if (!treeNode.getAttributeAsBoolean("folder"))
				{
					String href = treeNode.getAttributeAsString("href");
					Util.open(href);
					return;
				}
			}
		});
		vItem.setEnableIfCondition(new MenuItemIfFunction()
		{

			public boolean execute(Canvas target, Menu menu, MenuItem item)
			{
				TreeNode node = (TreeNode) jobFiles.getRecord(jobFiles.getEventRow());
				return !node.getAttributeAsBoolean("folder");
			}
		});
		pItem.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler()
		{
			public void onClick(MenuItemClickEvent event)
			{
				TreeNode treeNode = (TreeNode) jobFiles.getSelectedRecord();
				if (!treeNode.getAttributeAsBoolean("folder"))
				{
					String href = treeNode.getAttributeAsString("href");
					if (href.endsWith(".ps"))
						href = href.substring(0, href.length() - 3) + ".pdf" + "?pdf=1";
					Util.open(href);
					return;
				}
			}
		});
		pItem.setEnableIfCondition(new MenuItemIfFunction()
		{

			public boolean execute(Canvas target, Menu menu, MenuItem item)
			{
				TreeNode node = (TreeNode) jobFiles.getRecord(jobFiles.getEventRow());
				if (node.getAttributeAsBoolean("folder"))
					return false;
				String name = node.getAttribute("name");
				if (name.endsWith(".ps"))
					return true;
				else
					return false;
			}
		});
		menu.setItems(dItem, aItem, vItem, rItem, pItem);
		jobFiles.setContextMenu(menu);
		jobFiles.addDrawHandler(new DrawHandler()
		{
			public void onDraw(DrawEvent event)
			{
				Tree tree = jobFiles.getTree();
				tree.getRoot().setAttribute("servername", "");
				tree.setNameProperty("servername");
				tree.setPathDelim("/");
				tree.setIsFolderProperty("folder");
				String openProp = tree.getOpenProperty();
				jobRootNode.setAttribute(openProp, true);
			}
		});
	}

}
